import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';


import '../AppConfig/Config.dart';
import 'CheckRoutes/common/route_detail_page.dart';
import 'CheckRoutes/common/route_info_footer.dart';
import 'CheckRoutes/common/route_search_bar.dart';
import 'CheckRoutes/model/drive_route_model.dart';


class DrivingRouteView extends StatefulWidget {
  const DrivingRouteView({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<DrivingRouteView> createState() => _DrivingRouteViewState();
}

class _DrivingRouteViewState extends State<DrivingRouteView> {
  late BMFMapController myMapController;
  late  String stratCity="";
  String endCity="";
  String stratDetail="";
  String endDetail="";

  BMFPolyline? _polyline;

  bool _isShowSearchResultList = false;
  bool _isShowRouteInfoFooter = false;
  bool _isShowTrafficType = true;
  String _drivingPolicyTextValue = "最短时间";
  int _drivingPolicyIndex = 1;

  /// 驾车路线
  List<DriveRouteModel> _driveRoutes = [];
  DriveRouteModel? _selectedDriveRouteModel;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _onTapSearchDrivingRoute;
    print(widget.dataMap);
    stratCity=widget.dataMap['loadPlaceInfo'][0]['city'];
    stratDetail=widget.dataMap['loadPlaceInfo'][0]['address'];
    endCity=widget.dataMap['unloadPlaceInfo'][0]['city'];
    endDetail=widget.dataMap['unloadPlaceInfo'][0]['address'];
  }
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title: Text("查看路线", style: TextStyle(fontWeight: FontWeight.w300,color: Colors.black,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Stack(
        children: [
          generateMap(),
          _searchBar(),
          _searchResultListView(),
          _routeInfoFooter(),
        ],
      ),
    );
  }
  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) async {
    myMapController = controller;

    /// 地图加载回调
    myMapController.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });

    controller.setMapOnClickedOverlayCallback(callback: (BMFOverlay circle) {
      print('circle=${circle.toMap()}');
    });
  }

  /// 设置地图参数
  BMFMapOptions initMapOptions() {
    BMFMapOptions mapOptions = BMFMapOptions(
        center: BMFCoordinate(widget.dataMap['loadPlaceInfo'][0]['latitude'], widget.dataMap['loadPlaceInfo'][0]['longitude']),
        zoomLevel: 12,
        mapPadding: BMFEdgeInsets(top: 0, left: 0, right: 0, bottom: 0));
    return mapOptions;
  }

  /// 创建地图
  Container generateMap() {
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: BMFMapWidget(
        onBMFMapCreated: onBMFMapCreated,
        mapOptions: initMapOptions(),
      ),
    );
  }

  /// 创建控制栏
  Widget generateControlBar() {
    throw UnimplementedError();
  }
  /// 检索
  void _onTapSearchDrivingRoute() async {
    // 地名规划路线
    BMFPlanNode from = BMFPlanNode(
      // cityName: _startCityName.text,
      // name: _startPlanNodeName.text,
      pt: BMFCoordinate(widget.dataMap['loadPlaceInfo'][0]['latitude'], widget.dataMap['loadPlaceInfo'][0]['longitude']), // name 经纬度 二选一， 同时指定，经纬度优先
    );
    BMFPlanNode to = BMFPlanNode(
      // cityName: _endCityName.text,
      // name: _endPlanNodeName.text,
      pt: BMFCoordinate(widget.dataMap['unloadPlaceInfo'][0]['latitude'],widget.dataMap['unloadPlaceInfo'][0]['longitude'] ), // name 经纬度 二选一， 同时指定，经纬度优先
    );

    /// 驾车检索参数设置
    BMFDrivingRoutePlanOption drivingRoutePlanOption =
    BMFDrivingRoutePlanOption(from: from, to: to);
    drivingRoutePlanOption.drivingRequestTrafficType = _isShowTrafficType
        ? BMFDrivingRequestTrafficType.PATH_AND_TRAFFICE
        : BMFDrivingRequestTrafficType.NONE;
    drivingRoutePlanOption.drivingPolicy =
    BMFDrivingPolicy.values[_drivingPolicyIndex];

    BMFDrivingRouteSearch drivingRouteSearch = BMFDrivingRouteSearch();

    /// 检索回调
    drivingRouteSearch.onGetDrivingRouteSearchResult(
        callback: _onGetBMFDrivingRouteResult);

    bool result =
    await drivingRouteSearch.dringRouteSearch(drivingRoutePlanOption);

    if (result) {
      BrnToast.show("发起检索成功", context);
    } else {
      BrnToast.show("发起检索失败", context);

    }
  }

  /// 检索结果回调
  void _onGetBMFDrivingRouteResult(

      BMFDrivingRouteResult result, BMFSearchErrorCode errorCode) {
    if (errorCode != BMFSearchErrorCode.NO_ERROR) {
      var error = "检索失败" + "errorCode:${errorCode.toString()}";
      BrnToast.show(error, context);
      print(error);
      return;
    }
    /// 驾车结果路线
    _driveRoutes.clear();
    result.routes?.forEach((element) {

      DriveRouteModel model = DriveRouteModel.withModel(element) ;
      _driveRoutes.add(model);
    });

    result.routes?.forEach((element) {
      try {
        DriveRouteModel model = DriveRouteModel.withModel(element);
        _driveRoutes.add(model);
      } catch (e) {
        BrnToast.show("在处理路线时发生错误: $e", context);
      }
    });
    setState(() {
      _isShowRouteInfoFooter = false;
      _isShowSearchResultList = true;
      _onTapRouteItem(0);
    });
  }

  /// 选择路线
  void _onTapRouteItem(int idx) {

    setState(() {
      _isShowSearchResultList = false;
      _isShowRouteInfoFooter = true;
      _selectedDriveRouteModel = _driveRoutes[idx];
    });

    _addRoutePolyline();
  }

  /// 点击详情
  void _onTapDetail() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => RouteDetailPage(
          routeModel: _selectedDriveRouteModel,
        ),
      ),
    );
  }

  /// 路线 Polyline
  void _addRoutePolyline() {
    List<BMFMarker> markers = [];

    /// 起点marker
    BMFCoordinate? startCoord = _selectedDriveRouteModel?.startNode?.location;
    if (startCoord != null) {
      BMFMarker startMarker = BMFMarker.icon(
        position: startCoord,
        title: _selectedDriveRouteModel?.startNode?.title,
        icon: "lib/Images/resoures/icon_start.png",
      );
      markers.add(startMarker);
    }

    /// 终点marker
    BMFCoordinate? endCoord = _selectedDriveRouteModel?.endNode?.location;
    if (endCoord != null) {
      BMFMarker endMarker = BMFMarker.icon(
        position: endCoord,
        title: _selectedDriveRouteModel?.endNode?.title,
        icon: "lib/Images/resoures/icon_end.png",
      );
      markers.add(endMarker);
    }

    /// 驾车途径点marker
    _selectedDriveRouteModel?.wayPoints?.forEach((element) {
      BMFMarker marker = BMFMarker.icon(
        position: element.pt!,
        title: element.name,
        icon: "lib/Images/resoures/pin_red.png",
      );
      markers.add(marker);
    });

    /// 添加marker
    myMapController.cleanAllMarkers();
    myMapController.addMarkers(markers);

    /// 添加路线polyline
    if (_polyline != null) {
      myMapController.removeOverlay(_polyline!.id);
    }

    _polyline = BMFPolyline(
      width: 8,
      coordinates: _selectedDriveRouteModel!.routeCoordinates!,
      indexs: _selectedDriveRouteModel!.trafficIndexList!,
      textures: _isShowTrafficType ? _trafficTextures : ["lib/Images/resoures/traffic_texture_smooth.png"],
      dottedLine: false,
    );
    myMapController.addPolyline(_polyline!);

    /// 根据polyline设置地图显示范围
    BMFCoordinateBounds coordinateBounds =
    getVisibleMapRect(_polyline!.coordinates);

    myMapController.setVisibleMapRectWithPadding(
      visibleMapBounds: coordinateBounds,
      insets: EdgeInsets.only(top: 65.0, bottom: 70.0, left: 10, right: 10),
      animated: true,
    );
  }
  /// 获取地图显示区域
  BMFCoordinateBounds getVisibleMapRect(List<BMFCoordinate> coordinates) {
    BMFCoordinate fisrt = coordinates[0];
    double leftBottomX = fisrt.latitude;
    double leftBottomY = fisrt.longitude;
    double rightTopX = fisrt.latitude;
    double rightTopY = fisrt.longitude;

    for (BMFCoordinate coordinate in coordinates) {
      if (coordinate.latitude < leftBottomX) {
        leftBottomX = coordinate.latitude;
      }

      if (coordinate.longitude < leftBottomY) {
        leftBottomY = coordinate.longitude;
      }

      if (coordinate.latitude > rightTopX) {
        rightTopX = coordinate.latitude;
      }

      if (coordinate.longitude > rightTopY) {
        rightTopY = coordinate.longitude;
      }
    }

    BMFCoordinate leftBottom = BMFCoordinate(leftBottomX, leftBottomY);
    BMFCoordinate rightTop = BMFCoordinate(rightTopX, rightTopY);

    BMFCoordinateBounds coordinateBounds =
    BMFCoordinateBounds(northeast: rightTop, southwest: leftBottom);

    return coordinateBounds;
  }
  /// search bar
  Widget _searchBar() {
    return Container(
      child: Column(
        children: [
          RouteSearchBar(
            startCityController:  TextEditingController(text: stratCity),
            startController:  TextEditingController(text: stratDetail),
            endCityController: TextEditingController(text: endDetail),
            endController: TextEditingController(text: endDetail),
            callback: _onTapSearchDrivingRoute,
          ),
          // _otherSearchParamBar(),
        ],
      ),
    );
  }

  /// 驾车策略
  Widget _otherSearchParamBar() {
    return Container(
      color: MyColors.themeColor,
      padding: EdgeInsets.only(left: 5.0, right: 5.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: Container(
              alignment: Alignment.center,
              height: 30,
              child: Row(
                children: [
                  Text(
                    "驾车策略：",
                    style: _searchBarTextStyle,
                  ),
                  DropdownButton(
                    value: _drivingPolicyTextValue,
                    style: _searchBarTextStyle,
                    dropdownColor: Color(0xFF22253D),
                    iconEnabledColor: Colors.white,
                    underline: SizedBox(),
                    items: [
                      DropdownMenuItem(
                        child: Text(
                          "躲避拥堵",
                          style: _searchBarTextStyle,
                        ),
                        value: "躲避拥堵",
                        onTap: () => _drivingPolicyIndex = 0,
                      ),
                      DropdownMenuItem(
                        child: Text(
                          "最短时间",
                          style: _searchBarTextStyle,
                        ),
                        value: "最短时间",
                        onTap: () => _drivingPolicyIndex = 1,
                      ),
                      DropdownMenuItem(
                        child: Text("最短路程"),
                        value: "最短路程",
                        onTap: () => _drivingPolicyIndex = 2,
                      ),
                      DropdownMenuItem(
                        child: Text("少走高速"),
                        value: "少走高速",
                        onTap: () => _drivingPolicyIndex = 3,
                      ),
                    ],
                    onChanged: _dropdownButtonOnChange,
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Container(
                alignment: Alignment.center,
                child: Row(
                  children: [
                    SizedBox(width: 5),
                    Image.asset(
                      _isShowTrafficType
                          ? "lib/Images/resoures/selected_box.png"
                          : "lib/Images/resoures/unselected_box.png",color:Colors.white,
                      width: 15,
                      height: 15,
                    ),
                    SizedBox(width: 5),
                    Text(
                      "是否展示路况",
                      style: _searchBarTextStyle,
                    ),
                  ],
                ),
              ),
              onTap: () {
                _isShowTrafficType = !_isShowTrafficType;
                setState(() {});
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 驾车策略下拉菜单
  void _dropdownButtonOnChange(value) {
    setState(() {
      _drivingPolicyTextValue = value;
    });
  }

  /// 搜索结果列表
  Widget _searchResultListView() {
    return Positioned(
      top: 80,
      left: 0,
      right: 0,
      bottom: 0,
      child: Visibility(
        visible: _isShowSearchResultList,
        child: Container(
          color: Color(0xFFf7f7f7),
          child: ListView.builder(
            itemBuilder: _itemBuilder,
            itemCount: _driveRoutes.length,
          ),
        ),
      ),
    );
  }

  /// 搜索结果列表item
  Widget _itemBuilder(BuildContext context, int index) {
    DriveRouteModel model = _driveRoutes[index];
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        padding: EdgeInsets.only(left: 10, right: 10, top: 10),
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(4.0))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "路线${index + 1}：",
                style: _itemTitleStyle,
              ),
              Text(
                "${model.duration}（${model.distance}）",
                style: _itemSubTitleStyle,
              ),
              Text(
                "🚥：${model.lightNum}个     拥堵长度：${model.congestionMetres}米",
                style: _itemSubTitleStyle,
              ),
            ],
          ),
        ),
      ),
      onTap: () => _onTapRouteItem(index),
    );
  }

  /// 路线信息
  Widget _routeInfoFooter() {
    return Positioned(
      left: 15,
      right: 15,
      bottom: 15,
      child: Visibility(
        visible: _isShowRouteInfoFooter,
        child: RouteInfoFooter(
          duration: _selectedDriveRouteModel?.duration,
          distance: _selectedDriveRouteModel?.distance,
          onTapDetailBtn: _onTapDetail,
        ),
      ),
    );
  }
}

final _searchBarTextStyle = TextStyle(
  color: Colors.white,
  fontSize: 13,
  fontWeight: FontWeight.w400,
);

final _itemTitleStyle = TextStyle(
  color: Color(0xFF333333),
  fontSize: 15,
  fontWeight: FontWeight.w600,
);

final _itemSubTitleStyle = TextStyle(
  color: Color(0xFF333333),
  fontSize: 14,
  fontWeight: FontWeight.w500,
);

final _trafficTextures = [
  "lib/Images/resoures/traffic_texture_unknown.png",
  "lib/Images/resoures/traffic_texture_smooth.png",
  "lib/Images/resoures/traffic_texture_slow.png",
  "lib/Images/resoures/traffic_texture_congestion.png",
];